package com.kylewang.pomodoro.helper;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.kylewang.pomodoro.model.TaskModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import lombok.NonNull;

public class DBManager {
    public interface DBApiCallBack<T> {
        void onResponse(ArrayList<T> models);
        void onError(Exception error);
    }

    private static FirebaseFirestore db = FirebaseFirestore.getInstance();

    public static FirebaseFirestore getDB() {
        return db;
    }

    public static void updateTask(TaskModel item) {
        DocumentReference docRef = DBManager.getDB().collection("tasks").document(item.getTid());
        docRef.update(JsonUtil.toMap(item));
    }

    public static void fetchTasks(String ownerid, DBApiCallBack<TaskModel> callback) {
        if (ownerid == null || ownerid.length() == 0) {
            return;
        }
        DBManager.getDB().collection("tasks").whereEqualTo("ownerid", ownerid)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        ArrayList<TaskModel> arr = new ArrayList<>();
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                TaskModel taskModel = JsonUtil.fromMap(document.getData(), TaskModel.class);
                                taskModel.setTid(document.getId());
                                arr.add(taskModel);
                            }
                        }
                        callback.onResponse(arr);
                    }
                });
    }

    public static void addNewTask(String name, String ownerId, DBApiCallBack callback) {
        TaskModel newtask = TaskModel.generateBlankTaskItem();
        newtask.setName(name);
        newtask.setOwnerid(ownerId);
        Map<String, Object> taskMap = JsonUtil.toMap(newtask);
        DBManager.getDB().collection("tasks")
                .add(taskMap)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        newtask.setTid(documentReference.getId());
                        ArrayList<TaskModel> arr = new ArrayList<>();
                        arr.add(newtask);
                        callback.onResponse(arr);
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        callback.onError(e);
                    }
                });
    }

    public static void commitFeedBack(String content, DBApiCallBack<DocumentReference> callback) {
        if (content.length() == 0) {
            return;
        }
        HashMap<String, Object> feedbackMap = new HashMap<>();
        feedbackMap.put("content", content);
        if (Utils.isLogin()) {
            feedbackMap.put("uid", Utils.currentUser().getUid());
        }
        DBManager.getDB().collection("feedback")
                .add(feedbackMap)
                .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        callback.onResponse(null);
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@lombok.NonNull Exception e) {
                        callback.onError(e);
                    }
                });
    }
}
